package com.tsugun.mediaplayer.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.service.MusicAudioService;
import com.tsugun.mediaplayer.presenter.utils.SystemHelper;
import com.tsugun.mediaplayer.view.loader.MediaImageLoad;
import com.tsugun.mediaplayer.view.widget.LockScreenLayout;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LockActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "LockActivity";
    // intent action
    public static final String INTENT_FILTER_MUSIC_PLAY_INFO = "com.tsugun.mediaplayer.intent.info";
    public static final String INTENT_FILTER_MUSIC_PLAY_STATE = "com.tsugun.mediaplayer.intent.state";
    public static final String INTENT_FILTER_CONTROL = "com.tsugun.mediaplayer.intent.control";
    // extra
    public static final String EXTRA_MUSIC_ID = "musicId";
    public static final String EXTRA_STATE = "state";

    public static final String EXTRA_CONTROL = "control";
    public static final String EXTRA_CONTROL_PLAY = "play";
    public static final String EXTRA_CONTROL_NEXT = "next";
    public static final String EXTRA_CONTROL_PREV = "prev";

    @BindView(R.id.id_lock_root)
    LockScreenLayout mLSLRoot;
    @BindView(R.id.id_lock_album)
    ImageView mIvAlbum;
    @BindView(R.id.id_lock_time)
    TextView mTvTime;
    @BindView(R.id.id_lock_date)
    TextView mTvDate;
    @BindView(R.id.id_lock_week)
    TextView mTvWeek;
    @BindView(R.id.id_lock_lyric)
    TextView mTvLyric;
    @BindView(R.id.id_lock_title)
    TextView mTvTitle;
    @BindView(R.id.id_lock_sub_title)
    TextView mTvSubTitle;
    @BindView(R.id.id_lock_prev)
    ImageButton mIbPrev;
    @BindView(R.id.id_lock_play)
    ImageButton mIbPlay;
    @BindView(R.id.id_lock_next)
    ImageButton mIbNext;
    @BindView(R.id.id_lock_favorite)
    ImageButton mIbFavorite;

    private ListProvider mProvider;
    private String mMusicId; // 接收到的音乐id
    private String mOldId; // 上一次更新界面的id
    private boolean isTouch; // 是否正在滑屏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 显示在锁屏之上
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.activity_lock);
        ButterKnife.bind(this);

        initView();
        initData();
        bindView();
    }

    private void initView() {

    }

    private void initData() {
        mProvider = getListProvider();
        mMusicId = getIntent().getStringExtra(EXTRA_MUSIC_ID);
        mOldId = mMusicId;
        isTouch = false;
    }

    private void bindView() {
        mLSLRoot.setScreenMoveEvent(mMoveEventListener);
        mIbPrev.setOnClickListener(this);
        mIbPlay.setOnClickListener(this);
        mIbNext.setOnClickListener(this);
        mIbFavorite.setOnClickListener(this);
        initMusicPlayInfoReceiver();
        updateLockInfo();
        updateLockDate();
    }

    /**
     * 初始化音乐播放信息广播接收器
     */
    private void initMusicPlayInfoReceiver() {
        IntentFilter intentFilter = new IntentFilter(INTENT_FILTER_MUSIC_PLAY_INFO);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(INTENT_FILTER_MUSIC_PLAY_STATE);
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_lock_prev:
                Log.d(TAG, "onClick: prev");
                skipToPrev();
                break;
            case R.id.id_lock_play:
                Log.d(TAG, "onClick: play");
                play();
                break;
            case R.id.id_lock_next:
                Log.d(TAG, "onClick: next");
                skipToNext();
                break;
            case R.id.id_lock_favorite:
                Log.d(TAG, "onClick: favorite");
                addFavorite();
                break;
        }
    }

    /**
     * 加入喜欢列表
     */
    private void addFavorite() {
        mProvider.setFavorite(mMusicId);
        setButtonStyle();
    }

    /**
     * 下一首
     */
    private void skipToNext() {
        Intent intent = new Intent(INTENT_FILTER_CONTROL);
        intent.putExtra(EXTRA_CONTROL, EXTRA_CONTROL_NEXT);
        sendBroadcast(intent);
    }

    /**
     * 播放/暂停
     */
    private void play() {
        Intent intent = new Intent(INTENT_FILTER_CONTROL);
        intent.putExtra(EXTRA_CONTROL, EXTRA_CONTROL_PLAY);
        sendBroadcast(intent);
    }

    /**
     * 上一首
     */
    private void skipToPrev() {
        Intent intent = new Intent(INTENT_FILTER_CONTROL);
        intent.putExtra(EXTRA_CONTROL, EXTRA_CONTROL_PREV);
        sendBroadcast(intent);
    }

    /**
     * 锁屏解锁滑动事件监听
     */
    private LockScreenLayout.ScreenMoveEventListener mMoveEventListener = new LockScreenLayout
            .ScreenMoveEventListener() {
        @Override
        public void onScroll(int distance) {
            isTouch = true;
        }

        @Override
        public void onOpen() {
            isTouch = false;
            if (mOldId.equals(mMusicId)) {
                return;
            }
            updateLockInfo();
            updateLockDate();
        }

        @Override
        public void onClose() {
            isTouch = false;
            finish();
        }
    };

    /**
     * 设置一个广播接收器，接收音乐播放消息
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_TIME_TICK:
                    // 每分钟收到系统时间变化广播
                    updateLockDate();
                    break;
                case INTENT_FILTER_MUSIC_PLAY_INFO:
                    mMusicId = intent.getStringExtra(EXTRA_MUSIC_ID);
                    updateLockInfo();
                    break;
                case INTENT_FILTER_MUSIC_PLAY_STATE:
                    setButtonStyle();
                    break;
            }
        }
    };

    /**
     * 更新锁屏时间
     */
    private void updateLockDate() {
        if (isTouch) {
            return;
        }
        mTvTime.setText(SystemHelper.INSTANCE.getSystemTime());
        mTvDate.setText(SystemHelper.INSTANCE.getSystemDate());
        mTvWeek.setText(SystemHelper.INSTANCE.getSystemWeek());
    }

    /**
     * 更新锁屏界面
     */
    private void updateLockInfo() {
        if (isTouch) {
            return;
        }
        MusicModel musicModel = mProvider.getMusic(mMusicId);
        setButtonStyle();
        mTvTitle.setText(musicModel.getTitle());
        mTvSubTitle.setText(musicModel.getArtist());
        // 清除缓存后无法正常使用
//        String artUri = musicModel.getImageUrl();
//        if (artUri != null) {
//            mIvAlbum.setImageBitmap(BitmapFactory.decodeFile(artUri));
//        } else {
//            mIvAlbum.setImageResource(R.drawable.ic_music_default);
//        }
        MediaImageLoad.loadBitmap(SystemHelper.INSTANCE.getWallpaper(LockActivity.this), mIvAlbum);
        MediaImageLoad.lockImageLoad(musicModel, mIvAlbum);
        mOldId = mMusicId;
    }

    /**
     * 设置播放/暂停按钮
     */
    private void setButtonStyle() {
        // 设置播放按钮
        if (MusicAudioService.Companion.getMState() != PlaybackStateCompat.STATE_PLAYING) {
            mIbPlay.setImageResource(R.drawable.ic_play_arrow_light);
        } else {
            mIbPlay.setImageResource(R.drawable.ic_pause_light);
        }
        // 设置喜欢按钮
        if (mProvider.isFavorite(mMusicId)) {
            mIbFavorite.setImageResource(R.drawable.ic_favorite_light);
        } else {
            mIbFavorite.setImageResource(R.drawable.ic_favorite_border_black);
        }
    }

    @Override
    protected void onMusicLoadFailed() {

    }

    @Override
    protected void onMusicLoadComplete(ListProvider musicListProvider) {

    }

    @Override
    public void onSettingChanged() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onBackPressed() {
    }
}
